package com.intpro.demo.Service;

import com.intpro.demo.DAO.User;
import com.intpro.demo.Utils.AESToken;
import com.intpro.demo.Utils.CodeException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

@Service
public class UserService
{

	@Autowired
	MongoTemplate mongoTemplate;
	private final String base = "api/files/base.jpg";

	public User addUser(User user) throws Exception
	{
		user.password = AESToken.encrypt(user.password);
		user.picUrl = base;
		user.nickName = user.account;
		mongoTemplate.insert(user);
		return user;
	}

	public User checkPswByAccount(String account, String psw) throws Exception
	{
		String t = AESToken.encrypt(psw);
		Query q1 = new Query(Criteria.where("account").is(account));
		User u = mongoTemplate.findOne(q1, User.class);
		if (u == null)
		{
			return null;
		}
		//String tmp = AESToken.decrypt(u.password);
		//System.out.println(tmp);
		if (!u.password.equals(t))
		{
			u.id = -1;
		}
		return u;
	}

	public User checkPswByEmail(String email, String psw) throws Exception
	{
		String t = AESToken.encrypt(psw);
		Query q1 = new Query(Criteria.where("email").is(email));
		User u = mongoTemplate.findOne(q1, User.class);
		if (u == null)
		{
			return null;
		}
		if (!u.password.equals(t))
		{
			u.id = -1;
		}
		return u;
	}

	public User getUserById(long id)
	{
		Query q1 = new Query(Criteria.where("id").is(id));
		return mongoTemplate.findOne(q1, User.class);
	}

	public User getUserByAccount(String account)
	{
		Query q1 = new Query(Criteria.where("account").is(account));
		return mongoTemplate.findOne(q1, User.class);
	}
	public List<User> getUsers()
	{
		return mongoTemplate.find(new Query(), User.class);
	}

	public void updateUser(User user)
	{
		mongoTemplate.save(user);
	}

}
